﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>货品管理 - 编辑货品信息</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css" />
    <style>
        /* 保留所有添加页面的样式 */
        .custom-active-action, .custom-inactive-action {
            color: red;
            font-size: 12px;
            font-weight: bold;
            width: 100%;
            text-align: center;
        }

        .el-switch__action {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .basicInfo {
            width: 82%;
            background-color: #fff;
            padding: 20px 0 10px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .stockInfo {
            width: 82%;
            min-height: 530px;
            background-color: #fff;
            padding-top: 10px;
            margin-top: 50px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .uploadAttachment {
            width: 82%;
            min-height: 450px;
            background-color: #fff;
            padding-top: 10px;
            margin-top: 50px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .saveBlock {
            display: grid;
            place-items: center;
            position: sticky;
            bottom: 0;
            width: 100%;
            height: 60px;
            background-color: #fff;
            z-index: 20;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .titleH {
            margin-left: 40px;
        }

        .orderTable {
            margin: 0 auto;
            width: 80%;
        }

        .imp {
            color: red;
        }

        .orderTable tbody tr td {
            padding: 20px;
        }

        .custom-readonly-input .el-input__inner {
            background-color: #f0f0f0 !important;
            padding: 0px;
        }

        .custom-readonly-input .el-input__wrapper {
            background-color: #f0f0f0 !important;
        }

        .el-tree {
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            padding: 10px;
            max-height: 400px;
            overflow-y: auto;
        }

        .tree-title {
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .detailBlock {
            padding-left: 30px;
        }

        .uploadAttach {
            padding-top: 30px;
            padding-left: 60px;
        }

        .searchBlock {
            display: inline;
        }

        .buttonBlock {
            display: inline;
            margin-left: 335px;
        }

        .el-table__footer-wrapper {
            font-weight: bold;
            background-color: #f5f7fa;
        }

            .el-table__footer-wrapper td {
                text-align: center !important;
            }

        .promptWord {
            color: #606266;
        }

        .upload-demo {
            display: inline-block;
        }

        .btnBlock {
            margin-left: auto;
            padding: 10px 20px 10px 10px;
        }

        .basicInfoForm .el-form-item {
            margin-bottom: 15px;
        }

        .form-row {
            display: flex;
            flex-wrap: wrap;
            margin: 0 -10px;
        }

        .form-col {
            flex: 0 0 50%;
            padding: 0 10px;
            box-sizing: border-box;
        }

        .full-width {
            flex: 0 0 100%;
        }

        .form-container {
            padding: 0 40px;
        }

        .required-label::before {
            content: '*';
            color: #F56C6C;
            margin-right: 4px;
        }

        .stockTable {
            margin: 20px 40px;
            width: 95%;
            overflow-x: auto;
        }

            .stockTable .el-table {
                width: 100%;
                min-width: 1000px;
                table-layout: fixed;
            }

                .stockTable .el-table th {
                    background-color: #f5f7fa;
                    text-align: center;
                }

                .stockTable .el-table td {
                    text-align: center;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

                .stockTable .el-table .el-table__header-wrapper .el-table__header th:nth-child(1) {
                    width: 120px;
                }

                .stockTable .el-table .el-table__header-wrapper .el-table__header th:nth-child(2),
                .stockTable .el-table .el-table__header-wrapper .el-table__header th:nth-child(3) {
                    width: 140px;
                }

                .stockTable .el-table .el-table__header-wrapper .el-table__header th:nth-child(4),
                .stockTable .el-table .el-table__header-wrapper .el-table__header th:nth-child(5) {
                    width: 160px;
                }

                .stockTable .el-table .el-table__header-wrapper .el-table__header th:nth-child(6) {
                    width: 200px;
                }

                .stockTable .el-table .el-table__header-wrapper .el-table__header th:nth-child(7) {
                    width: 100px;
                }

        .input-with-unit {
            display: flex;
            align-items: center;
            justify-content: center;
        }

            .input-with-unit .el-input {
                width: 120px;
                margin-right: 8px;
            }

        .unit-text {
            color: #909399;
            font-size: 14px;
        }

        .add-remove-buttons {
            margin: 10px 40px;
        }

        .cascader-item {
            display: flex;
            align-items: center;
        }

        .cascader-select {
            width: 100%;
        }

        /* 新增：图片预览样式 */
        .image-upload-container {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 20px;
        }

        .image-item {
            position: relative;
            width: 120px;
            height: 120px;
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            overflow: hidden;
        }

        .image-preview {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .image-actions {
            position: absolute;
            top: 0;
            right: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            padding: 4px;
        }

        .image-action-btn {
            color: white;
            cursor: pointer;
            margin: 0 2px;
        }

        /* 新增：附件列表样式 */
        .attachment-list {
            margin-top: 20px;
        }

        .attachment-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            margin-bottom: 8px;
        }

        .attachment-info {
            display: flex;
            align-items: center;
        }

        .attachment-icon {
            margin-right: 8px;
            color: #409EFF;
        }

        /* 新增：加载状态样式 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
    </style>
</head>
<body>
    <div id="app" class="common-layout">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-overlay">
            <el-icon class="is-loading" style="font-size: 40px;">
                <loading />
            </el-icon>
            <span style="margin-left: 10px;">正在加载货品数据...</span>
        </div>

        <!-- 基础信息 -->
        <div class="basicInfo" style=" margin: 20px;">
            <h4 class="titleH">基础信息</h4>
            <hr />
            <div class="form-container">
                <el-form :model="form" label-width="120px" class="basicInfoForm">
                    <!-- 货品名称（独占一行） -->
                    <div class="form-row">
                        <div class="form-col full-width">
                            <el-form-item label="货品名称" class="required-label" required>
                                <el-input v-model="form.goodsName" placeholder="请输入" style="width: 100%" />
                            </el-form-item>
                        </div>
                    </div>

                    <!-- 货品编号 + 货品类型ID -->
                    <div class="form-row">
                        <div class="form-col">
                            <el-form-item label="货品编号" class="required-label" required>
                                <el-input v-model="form.goodsCode" placeholder="不输入则自动获取编号" style="width: 100%" readonly />
                            </el-form-item>
                        </div>
                        <div class="form-col">
                            <el-form-item label="货品类型" class="required-label" required>
                                <div class="cascader-item">
                                    <el-cascader v-model="form.goodsTypeId"
                                                 :options="goodsTypeTree"
                                                 :props="cascaderProps"
                                                 placeholder="请选择货品类型"
                                                 clearable
                                                 class="cascader-select"
                                                 v-on:change="handleGoodsTypeChange" />
                                </div>
                                <el-button type="text" size="small" style="margin-left: 8px;">设置</el-button>
                            </el-form-item>
                        </div>
                    </div>
                    <!-- 供应商 + 客户 -->
                    <div class="form-row">
                        <div class="form-col">
                            <el-form-item label="关联供应商" class="required-label" required>
                                <el-select v-model="form.supplierId" placeholder="请选择供应商" style="width: 100%">
                                    <el-option v-for="item in supplierOptions"
                                               :key="item.id"
                                               :label="item.name"
                                               :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </div>
                        <div class="form-col">
                            <el-form-item label="关联客户" class="required-label" required>
                                <el-select v-model="form.customerId" placeholder="请先选择供应商" style="width: 100%" :disabled="!form.supplierId">
                                    <el-option v-for="item in customerOptions"
                                               :key="item.id"
                                               :label="item.name"
                                               :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </div>
                    </div>

                    <!-- 规格 + 采购参考价/元 -->
                    <div class="form-row">
                        <!-- 新规格下拉框代码 -->
                        <div class="form-col">
                            <el-form-item label="规格">
                                <el-select v-model="form.specification" placeholder="请选择规格" style="width: 100%">
                                    <!-- 尺寸类规格 -->
                                    <el-option label="10cm×10cm" value="10cm×10cm"></el-option>
                                    <el-option label="20cm×30cm" value="20cm×30cm"></el-option>
                                    <el-option label="A4尺寸（210mm×297mm）" value="A4尺寸（210mm×297mm）"></el-option>
                                    <el-option label="均码" value="均码"></el-option>
                                    <el-option label="S码" value="S码"></el-option>
                                    <el-option label="M码" value="M码"></el-option>
                                    <el-option label="L码" value="L码"></el-option>
                                    <el-option label="XL码" value="XL码"></el-option>
                                    <!-- 重量类规格 -->
                                    <el-option label="100g" value="100g"></el-option>
                                    <el-option label="500g" value="500g"></el-option>
                                    <el-option label="1kg" value="1kg"></el-option>
                                    <el-option label="2.5kg" value="2.5kg"></el-option>
                                    <!-- 容量类规格 -->
                                    <el-option label="50ml" value="50ml"></el-option>
                                    <el-option label="100ml" value="100ml"></el-option>
                                    <el-option label="500ml" value="500ml"></el-option>
                                    <el-option label="1L" value="1L"></el-option>
                                    <el-option label="5L" value="5L"></el-option>
                                    <!-- 材质/版本类规格 -->
                                    <el-option label="不锈钢" value="不锈钢"></el-option>
                                    <el-option label="食品级塑料" value="食品级塑料"></el-option>
                                    <el-option label="棉质" value="棉质"></el-option>
                                    <el-option label="硅胶" value="硅胶"></el-option>
                                    <el-option label="标准版" value="标准版"></el-option>
                                    <el-option label="升级版" value="升级版"></el-option>
                                    <el-option label="豪华版" value="豪华版"></el-option>
                                    <el-option label="定制版" value="定制版"></el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                        <el-form-item label="采购参考价/元">
                            <el-input v-model="form.purchaseReferencePrice" type="number" step=".50" placeholder="请输入" style="width: 100%" v-on:change="checkNonNegative('采购参考价', form.purchaseReferencePrice, 'form', 'purchaseReferencePrice')" />
                        </el-form-item>
                    </div>

                    <!-- 销售参考价/元 + 显示顺序 -->
                    <div class="form-row">
                        <div class="form-col">
                            <el-form-item label="销售参考价/元">
                                <el-input v-model="form.salesReferencePrice" type="number" step="0.50" placeholder="请输入" style="width: 100%" v-on:change="checkNonNegative('销售参考价', form.salesReferencePrice, 'form', 'salesReferencePrice')" />
                            </el-form-item>
                        </div>
                        <div class="form-col">
                            <el-form-item label="显示顺序">
                                <el-input v-model="form.displayOrder" type="number" placeholder="请输入" style="width: 100%" v-on:change="checkNonNegative('显示顺序', form.displayOrder, 'form', 'displayOrder')" />
                            </el-form-item>
                        </div>
                    </div>

                    <!-- 保质期管理相关行修改 -->
                    <div class="form-row">
                        <div class="form-col">
                            <el-form-item label="状态" required>
                                <el-radio-group v-model="form.status">
                                    <el-radio label="1">启用</el-radio>
                                    <el-radio label="2">停用</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </div>
                        <div class="form-col">
                            <el-form-item label="保质期管理" required>
                                <el-switch v-model="isShelfLifeEnabled"
                                           active-color="#409EFF"
                                           inactive-color="#C0C4CC"
                                           style="--el-switch-width: 50px; --el-switch-height: 24px;">
                                    <template #active-text>开启</template>
                                    <template #inactive-text>关闭</template>
                                </el-switch>
                            </el-form-item>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-col">
                            <el-form-item label="保质期" :required="isShelfLifeEnabled">
                                <el-input v-model="form.shelfLife"
                                          type="number"
                                          placeholder="请输入"
                                          style="width: 200px; margin-right: 10px;"
                                          :disabled="!isShelfLifeEnabled"
                                          v-on:change="checkNonNegative('保质期', form.shelfLife, 'form', 'shelfLife')"></el-input>
                                <el-select v-model="form.shelfLifeType"
                                           placeholder="请选择"
                                           style="width: 100px"
                                           :disabled="!isShelfLifeEnabled">
                                    <el-option label="天" value="天"></el-option>
                                    <el-option label="月" value="月"></el-option>
                                    <el-option label="年" value="年"></el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                        <div class="form-col">
                            <el-form-item label="预警天数(天)" :required="isShelfLifeEnabled">
                                <el-input v-model="form.warningDays"
                                          type="number"
                                          placeholder="请输入"
                                          style="width: 300px"
                                          :disabled="!isShelfLifeEnabled"
                                          v-on:change="checkNonNegative('预警天数', form.warningDays, 'form', 'warningDays')" />
                            </el-form-item>
                        </div>
                    </div>

                    <!-- 备注 -->
                    <div class="form-row">
                        <div class="form-col full-width">
                            <el-form-item label="备注">
                                <el-input v-model="form.remarks" type="textarea" placeholder="请输入" style="width: 100%" />
                            </el-form-item>
                        </div>
                    </div>
                </el-form>
            </div>
        </div>
        <!-- 库存信息部分 -->
        <div class="stockInfo" style="margin: 20px;">
            <h4 class="titleH">库存信息</h4>
            <hr />
            <!-- 关键修改：使用flex容器分离左右元素 -->
            <div style="display: flex; align-items: center; justify-content: space-between; margin: 0 40px 10px;">
                <!-- 左侧：添加/移除按钮 -->
                <div class="add-remove-buttons">
                    <el-button type="success" v-on:click="openWarehouseModal">添加</el-button>
                    <el-button type="danger" v-on:click="removeWarehouse">移除</el-button>
                </div>

                <!-- 右侧：初始化库存开关 -->
                <div style="display: flex; align-items: center;">
                    <el-switch v-model="isInitialStockEnabled"
                               active-color="#409EFF"
                               inactive-color="#C0C4CC"
                               style="--el-switch-width: 50px; --el-switch-height: 24px; margin-right: 10px;">
                        <template #active-text>开启</template>
                        <template #inactive-text>关闭</template>
                    </el-switch>
                    <span>初始化库存</span>
                </div>
            </div>
            <!-- 库存表格 -->
            <div class="stockTable">
                <el-table :data="inventoryData"
                          style="width: 100%"
                          v-on:selection-change="handleInventorySelectionChange"
                          ref="inventoryTable"
                          stripe>
                    <!-- 其他列保持不变 -->
                    <el-table-column prop="warehouseName" label="期初仓库" width="120"></el-table-column>
                    <!-- 根据开关控制显示/隐藏初期库存列 -->
                    <el-table-column v-if="isInitialStockEnabled" label="期初库存" width="140">
                        <template #default="scope">
                            <div class="input-with-unit">
                                <el-input v-model.number="scope.row.initialStock"
                                          placeholder="请输入"
                                          readonly
                                          style="cursor: pointer;"></el-input>
                                <el-button type="text"
                                           size="small"
                                           v-on:click="openBatchManagement(scope.row)"
                                           style="margin-left: 5px;">
                                    批次
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="isInitialStockEnabled" label="期初库存金额" width="160">
                        <template #default="scope">
                            <div class="input-with-unit">
                                <el-input v-model.number="scope.row.initialAmount" placeholder="请输入" v-on:change="checkNonNegative('期初库存金额', scope.row.initialAmount, 'row', 'initialAmount', scope)"></el-input>
                                <span class="unit-text">元</span>
                            </div>
                        </template>
                    </el-table-column>
                    <!-- 库存上下限列 - 添加输入事件监听 -->
                    <el-table-column label="库存上限" width="160">
                        <template #default="scope">
                            <div style="display: flex; align-items: center; justify-content: center;">
                                <el-input v-model.number="scope.row.stockUpperLimit"
                                          placeholder="请输入"
                                          v-on:change="() => {checkStockLimit(scope.row); checkNonNegative('库存上限', scope.row.stockUpperLimit, 'row', 'stockUpperLimit', scope)}"></el-input>
                                <el-button v-if="inventoryData.length > 1"
                                           type="text"
                                           size="small"
                                           v-on:click="openBatchModal('upper')"
                                           style="margin-left: 5px;">
                                    批量
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="库存下限" width="160">
                        <template #default="scope">
                            <div style="display: flex; align-items: center; justify-content: center;">
                                <el-input v-model.number="scope.row.stockLowerLimit"
                                          placeholder="请输入"
                                          v-on:change="() => {checkStockLimit(scope.row); checkNonNegative('库存下限', scope.row.stockLowerLimit, 'row', 'stockLowerLimit', scope)}"></el-input>
                                <el-button v-if="inventoryData.length > 1"
                                           type="text"
                                           size="small"
                                           v-on:click="openBatchModal('lower')"
                                           style="margin-left: 5px;">
                                    批量
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" width="200">
                        <template #default="scope">
                            <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                        <template #default="scope">
                            <el-button link
                                       type="primary"
                                       size="small"
                                       v-on:click="removeInventoryRow(scope.row)">
                                移除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <!-- 图片上传区域 -->
        <div class="uploadAttachment" style="margin: 20px;">
            <h4 class="titleH">上传图片</h4>
            <hr />
            <div class="uploadAttach">
                <div class="uploadBtn">
                    <input type="file"
                           ref="imageInput"
                           v-on:change="handleImageUpload"
                           accept=".jpg,.jpeg,.png,.gif,.bmp"
                           multiple
                           style="display: none" />
                    <el-button type="primary" v-on:click="triggerImageInput">上传图片</el-button>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <span class="promptWord">您可以上传jpg、png、gif等格式的图片，单个文件最大200MB</span>
                </div>
                <div class="image-upload-container">
                    <div v-for="(image, index) in uploadedImages" :key="index" class="image-item">
                        <img :src="image.url" :alt="image.name" class="image-preview" />
                        <div class="image-actions">
                            <el-icon class="image-action-btn" v-on:click="previewImage(image)">
                                <zoom-in />
                            </el-icon>
                            <el-icon class="image-action-btn" v-on:click="removeImage(index)">
                                <delete />
                            </el-icon>
                        </div>
                    </div>
                </div>
                <el-dialog v-model="imagePreviewVisible" width="80%">
                    <img :src="previewImageUrl" alt="" class="w-full" />
                </el-dialog>
            </div>
        </div>

        <!-- 上传附件-->
        <div class="uploadAttachment" style="margin: 20px;">
            <h4 class="titleH">上传附件</h4>
            <hr />
            <div class="uploadAttach">
                <div class="uploadBtn">
                    <input type="file"
                           ref="fileInput"
                           v-on:change="handleFileUpload"
                           accept=".doc,.docx,.pdf,.rar,.zip"
                           multiple
                           style="display: none" />
                    <el-button type="primary" v-on:click="triggerFileInput">上传附件</el-button>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <span class="promptWord">您可以上传doc、pdf、rar、zip等格式的文件，单个文件最大200MB</span>
                </div>
                <div class="attachment-list">
                    <div v-for="(file, index) in uploadedFiles" :key="index" class="attachment-item">
                        <div class="attachment-info">
                            <el-icon class="attachment-icon">
                                <document />
                            </el-icon>
                            <span>{{ file.name }}</span>
                        </div>
                        <div class="attachment-actions">
                            <el-button size="small"
                                       type="text"
                                       style="color: #ff4d4f;"
                                       v-on:click="removeFile(index)">
                                删除
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <!-- 底部保存栏 -->
        <div class="saveBlock" style="margin: 20px;">
            <div class="btnBlock">
                <el-button v-on:click="closeDetail">关闭</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;<el-button>保存草稿</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;<el-button v-on:click="saveAndAdd" style="display: none;">保存并新增</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;<el-button type="success" v-on:click="submitForm">更新</el-button>
            </div>
        </div>


        <!-- 仓库选择模态框 -->
        <el-dialog v-model="warehouseModalVisible" title="添加仓库" width="60%">
            <div style="margin-bottom: 15px;">
                <el-input v-model="warehouseSearch" placeholder="搜索仓库名称或编码" style="width: 300px;"></el-input>
                <el-button type="primary" v-on:click="searchWarehouses" style="margin-left: 10px;">搜索</el-button>
            </div>

            <el-table :data="filteredWarehouses"
                      style="width: 100%"
                      v-on:selection-change="handleWarehouseSelectionChange"
                      ref="warehouseTable">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="warehouseName" label="仓库名称"></el-table-column>
                <el-table-column prop="warehouseCode" label="仓库编码"></el-table-column>
                <el-table-column prop="warehouseAddress" label="仓库地址"></el-table-column>
                <el-table-column prop="warehouseCapacity" label="仓库容量">
                    <template #default="scope">
                        {{ scope.row.warehouseCapacity }} ㎡
                    </template>
                </el-table-column>
            </el-table>

            <template #footer>
                <span class="dialog-footer">
                    <el-button v-on:click="warehouseModalVisible = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmWarehouseSelection">确认选择</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 批量设置模态框 -->
        <el-dialog v-model="batchModalVisible" :title="batchModalTitle" width="400px">
            <el-form label-width="80px">
                <el-form-item :label="batchType === 'upper' ? '库存上限' : '库存下限'">
                    <el-input v-model.number="batchValue" type="number" placeholder="请输入数值"></el-input>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button v-on:click="batchModalVisible = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmBatchSet">确认设置</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 批次管理模态框 -->
        <el-dialog v-model="batchManagementVisible" title="批次管理" width="600px">
            <el-table :data="batchList" style="width: 100%" border>
                <el-table-column prop="index" label="序号" width="80">
                    <template #default="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <!-- 批次管理模态框 - 数量列 -->
                <el-table-column prop="quantity" label="数量" width="120">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.quantity" placeholder="请输入" v-on:change="checkNonNegative('批次数量', scope.row.quantity, 'batch', 'quantity', scope)"></el-input>
                    </template>
                </el-table-column>
                <!-- 批次管理模态框 - 批次列 -->
                <el-table-column prop="batchNo" label="批次" width="120">
                    <template #default="scope">
                        <el-input v-model="scope.row.batchNo" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <!-- 批次管理模态框 - 生产日期列 -->
                <el-table-column prop="productionDate" label="生产日期" width="160">
                    <template #default="scope">
                        <el-date-picker v-model="scope.row.productionDate"
                                        type="date"
                                        format="YYYY/MM/DD"
                                        value-format="YYYY/MM/DD"
                                        placeholder="选择日期"
                                        :default-value="new Date()"
                                        :disabled-date="disabledFutureDate"></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template #default="scope">
                        <el-button type="text"
                                   v-if="batchList.length === 1"
                                   disabled
                                   style="color: #909399;">移除</el-button>
                        <el-button type="text"
                                   v-else
                                   v-on:click="removeBatch(scope.$index)"
                                   style="color: #F56C6C;">移除</el-button>
                        <el-button type="text"
                                   style="color: #67C23A;"
                                   v-on:click="addBatch">添加</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="display: flex; justify-content: space-between; margin-top: 10px;">
                <div>
                    合计：<span style="font-weight: bold;">{{ calculateTotalQuantity }}</span>
                </div>
                <div>
                    批次总数：<span style="font-weight: bold;">{{ batchList.length }}</span>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button v-on:click="batchManagementVisible = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmBatchManagement">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
    <script>
        const { createApp, reactive, ref, onMounted, watch, computed } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;

        const app = createApp({
            setup() {
                // ---------- 基础信息表单数据 ----------
                const form = reactive({
                    goodsId: 0,
                    goodsCode: '',
                    goodsName: '',
                    goodsTypeId: [], // 改为数组，用于存储级联选择的路径
                    customerId: '',
                    supplierId: '',
                    specification: '',
                    purchaseReferencePrice: 0,
                    salesReferencePrice: 0,
                    displayOrder: 0,
                    status: '1',
                    shelfStatus: '1',
                    shelfLife: 0,
                    shelfLifeType: '天',
                    warningDays: 0,
                    stockMin: 0,
                    stockMax: 0,
                    belowMin: 0,
                    aboveMax: 0,
                    goodsImagePath: '',
                    attachmentId: 0,
                    isDelete: '0',
                    createBy: 'admin',
                    createTime: new Date(),
                    updateBy: 'admin',
                    updateTime: new Date(),
                    remarks: ''
                });

                // 开关绑定的布尔值（true=开启，false=关闭）
                const isShelfLifeEnabled = ref(form.shelfStatus === '1');
                // 库存初始化开关（true=开启，false=关闭）
                const isInitialStockEnabled = ref(true);
                // 加载状态
                const loading = ref(true);

                // 监听开关变化，同步更新表单的 shelfStatus
                watch(isShelfLifeEnabled, (newVal) => {
                    form.shelfStatus = newVal ? '1' : '0';
                    // 关闭时清空保质期相关数据
                    if (!newVal) {
                        form.shelfLife = 0;
                        form.warningDays = 0;
                    }
                });

                // ---------- 级联选择器配置 ----------
                const cascaderProps = {
                    value: 'id',
                    label: 'name',
                    children: 'children',
                    checkStrictly: false,
                    emitPath: true,
                    expandTrigger: 'hover'
                };

                // ---------- 图片上传相关 ----------
                const imageInput = ref(null);
                const uploadedImages = ref([]);
                const imagePreviewVisible = ref(false);
                const previewImageUrl = ref('');

                // ---------- 附件上传相关 ----------
                const fileInput = ref(null);
                const uploadedFiles = ref([]);

                // ---------- 树形数据 ----------
                const goodsTypeTree = ref([]);

                // ---------- 下拉框数据源 ----------
                const customerOptions = ref([]);
                const supplierOptions = ref([]);
                const dictDateOptions = ref([]);

                // ---------- 构建树形结构函数 ----------
                const buildTree = (data, parentId = 0) => {
                    const tree = [];
                    for (const item of data) {
                        if (item.fId === parentId) {
                            const children = buildTree(data, item.id);
                            const node = {
                                id: item.id,
                                name: item.name,
                                fId: item.fId
                            };
                            if (children.length > 0) {
                                node.children = children;
                            }
                            tree.push(node);
                        }
                    }
                    return tree;
                };

                // ---------- 加载货品详情数据 ----------
                const loadGoodsDetail = async () => {
                    try {
                        // 从URL获取货品ID
                        const urlParams = new URLSearchParams(window.location.search);
                        const goodsId = urlParams.get('id');

                        if (!goodsId) {
                            ElMessage.error('未找到货品ID');
                            loading.value = false;
                            return;
                        }

                        form.goodsId = parseInt(goodsId);

                        // 加载货品详情
                        const detailResponse = await axios.post(`/BiProduct/Details?id=${form.goodsId}`);
                        if (detailResponse.data.code === 300) {
                            const goodsData = detailResponse.data.data;

                            // 填充表单数据
                            form.goodsCode = goodsData.goodsCode;
                            form.goodsName = goodsData.goodsName;
                            form.customerId = goodsData.customerId;
                            form.supplierId = goodsData.supplierId;
                            form.specification = goodsData.specification;
                            form.purchaseReferencePrice = goodsData.purchaseReferencePrice;
                            form.salesReferencePrice = goodsData.salesReferencePrice;
                            form.displayOrder = goodsData.displayOrder;
                            form.status = goodsData.status.toString();
                            form.shelfStatus = goodsData.shelfStatus.toString();
                            form.shelfLife = goodsData.shelfLife;
                            form.shelfLifeType = goodsData.shelfLifeType;
                            form.warningDays = goodsData.warningDays;
                            form.stockMin = goodsData.stockMin;
                            form.stockMax = goodsData.stockMax;
                            form.belowMin = goodsData.belowMin;
                            form.aboveMax = goodsData.aboveMax;
                            form.goodsImagePath = goodsData.goodsImagePath;
                            form.attachmentId = goodsData.attachmentId;
                            form.remarks = goodsData.remarks;

                            // 更新开关状态
                            isShelfLifeEnabled.value = form.shelfStatus === '1';

                            // 如果有货品类型信息，设置货品类型
                            // 注意：这里需要根据实际情况调整，因为货品类型是级联选择
                            if (goodsData.goodsTypeId) {
                                // 这里需要根据goodsTypeId找到对应的路径
                                // 简化处理：直接设置为单级
                                form.goodsTypeId = [goodsData.goodsTypeId];
                            }

                            // 加载现有图片（如果有）
                            if (goodsData.goodsImagePath) {
                                uploadedImages.value.push({
                                    name: '现有图片',
                                    url: goodsData.goodsImagePath,
                                    isExisting: true
                                });
                            }

                            // 加载库存信息
                            await loadInventoryData();

                            ElMessage.success('货品数据加载成功');
                        } else {
                            ElMessage.error('加载货品详情失败：' + detailResponse.data.msg);
                        }
                    } catch (error) {
                        console.error('加载货品详情失败：', error);
                        ElMessage.error('网络异常，加载货品详情失败');
                    } finally {
                        loading.value = false;
                    }
                };

                // ---------- 加载库存数据 ----------
                const loadInventoryData = async () => {
                    try {
                        // 根据实际情况调用库存信息接口
                        // 这里简化处理，假设直接使用现有数据
                        // 实际项目中需要根据goodsId加载库存信息
                        const inventoryResponse = await axios.post(`/BiProduct/GetInventoryByGoodsId?id=${ form.goodsId}`);
                        if (inventoryResponse.data.code === 200) {
                            inventoryData.value = inventoryResponse.data.data;
                        } else {
                            // 如果没有库存数据，保持空数组
                            inventoryData.value = [];
                        }
                    } catch (error) {
                        console.error('加载库存数据失败：', error);
                        inventoryData.value = [];
                    }
                };

                // ---------- 加载下拉框数据 ----------
                const loadSelectData = async () => {
                    try {
                        // 1. 加载货品类型
                        const typeRes = await axios.post('/BiProduct/ProductTypeAllync');
                        if (typeRes.data.code === 200) {
                            goodsTypeTree.value = buildTree(typeRes.data.data);
                        } else {
                            ElMessage.error('加载货品类型失败：' + typeRes.data.msg);
                        }

                        // 2. 加载客户信息
                        const customerRes = await axios.post('/BiProduct/CustomerAll');
                        if (customerRes.data.code === 200) {
                            customerOptions.value = customerRes.data.data;
                        } else {
                            ElMessage.error('加载客户信息失败：' + customerRes.data.msg);
                        }

                        // 3. 加载供应商信息
                        const supplierRes = await axios.post('/BiProduct/SupplierAll');
                        if (supplierRes.data.code === 200) {
                            supplierOptions.value = supplierRes.data.data;
                        } else {
                            ElMessage.error('加载供应商信息失败：' + supplierRes.data.msg);
                        }

                        // 4. 加载状态字典数据
                        const dictDateRes = await axios.post('/BiProduct/DictDate');
                        if (dictDateRes.data.code === 200) {
                            dictDateOptions.value = dictDateRes.data.data;
                            if (dictDateOptions.value.length > 0) {
                                form.status = dictDateOptions.value[0].id.toString();
                            }
                        } else {
                            ElMessage.error('加载状态数据失败：' + dictDateRes.data.msg);
                        }
                    } catch (error) {
                        ElMessage.error('网络异常，加载数据失败');
                        console.error('下拉框数据加载失败：', error);
                    }
                };

                // 货品类型选择变化处理
                const handleGoodsTypeChange = (value) => {
                    console.log('选中的货品类型路径:', value);
                };

                // ---------- 图片上传处理 ----------
                // 图片上传处理（本地暂存）
                const handleImageUpload = (event) => {
                    const files = event.target.files;
                    if (!files || files.length === 0) return;

                    for (let i = 0; i < files.length; i++) {
                        const file = files[i];
                        const reader = new FileReader();
                        reader.onload = (e) => {
                            uploadedImages.value.push({
                                file: file, // 暂存原始文件对象
                                name: file.name,
                                previewUrl: e.target.result // 本地预览URL
                            });
                        };
                        reader.readAsDataURL(file);
                    }

                    ElMessage.success(`已添加 ${files.length} 张图片到本地，提交货品后将自动上传`);
                    event.target.value = '';
                };

                // 图片预览（本地）
                const previewImage = (image) => {
                    previewImageUrl.value = image.previewUrl || image.url;
                    imagePreviewVisible.value = true;
                };

                const removeImage = (index) => {
                    uploadedImages.value.splice(index, 1);
                    ElMessage.info('图片已删除');
                };

                // ---------- 附件上传处理 ----------
                const triggerFileInput = () => {
                    fileInput.value.click();
                };

                // 附件上传处理（本地暂存）
                const handleFileUpload = (event) => {
                    const files = event.target.files;
                    if (!files || files.length === 0) return;

                    for (let i = 0; i < files.length; i++) {
                        const file = files[i];
                        uploadedFiles.value.push({
                            file: file, // 暂存原始文件对象
                            name: file.name
                        });
                    }

                    ElMessage.success(`已添加 ${files.length} 个附件到本地，提交货品后将自动上传`);
                    event.target.value = '';
                };
                const triggerImageInput = () => {
                    imageInput.value.click();
                };

                const removeFile = (index) => {
                    uploadedFiles.value.splice(index, 1);
                    ElMessage.info('文件已删除');
                };

                // 组件初始化时加载数据
                onMounted(() => {
                    loadSelectData().then(() => {
                        loadGoodsDetail();
                    });
                });

                // ---------- 新增：库存相关数据 ----------
                const inventoryData = ref([]);
                const selectedInventoryRows = ref([]);

                // 仓库选择相关
                const warehouseModalVisible = ref(false);
                const warehouseList = ref([]);
                const selectedWarehouses = ref([]);
                const warehouseSearch = ref('');

                // 批量设置相关
                const batchModalVisible = ref(false);
                const batchType = ref('');
                const batchValue = ref(0);
                const batchModalTitle = computed(() => {
                    return batchType.value === 'upper' ? '批量设置库存上限' : '批量设置库存下限';
                });

                // 验证库存上限是否大于下限
                const checkStockLimit = (row) => {
                    const upper = Number(row.stockUpperLimit) || 0;
                    const lower = Number(row.stockLowerLimit) || 0;
                    if (upper < lower) {
                        ElMessage.warning(`仓库【${row.warehouseName}】的库存上限不能小于下限，请修正`);
                    }
                };

                // ---------- 仓库选择逻辑 ----------
                const openWarehouseModal = async () => {
                    try {
                        const response = await axios.post('/BiProduct/WhAll');
                        if (response.data.code === 200) {
                            warehouseList.value = response.data.data;
                            warehouseModalVisible.value = true;
                        } else {
                            ElMessage.error('加载仓库列表失败：' + response.data.msg);
                        }
                    } catch (error) {
                        ElMessage.error('网络异常，加载仓库列表失败');
                    }
                };

                const handleWarehouseSelectionChange = (val) => {
                    selectedWarehouses.value = val;
                };

                const confirmWarehouseSelection = () => {
                    if (selectedWarehouses.value.length === 0) {
                        ElMessage.warning('请至少选择一个仓库');
                        return;
                    }

                    const existingWarehouseIds = inventoryData.value.map(item => item.warehouseId);
                    const newWarehouses = selectedWarehouses.value.filter(
                        wh => !existingWarehouseIds.includes(wh.warehouseId)
                    );

                    if (newWarehouses.length === 0) {
                        ElMessage.warning('所选仓库已全部添加');
                        warehouseModalVisible.value = false;
                        return;
                    }

                    newWarehouses.forEach(warehouse => {
                        const newId = inventoryData.value.length > 0
                            ? Math.max(...inventoryData.value.map(item => item.id)) + 1
                            : 1;

                        inventoryData.value.push({
                            id: newId,
                            warehouseId: warehouse.warehouseId,
                            warehouseName: warehouse.warehouseName,
                            warehouseCode: warehouse.warehouseCode,
                            initialStock: 0,
                            initialAmount: 0,
                            stockUpperLimit: form.stockMax,
                            stockLowerLimit: form.stockMin,
                            remark: ''
                        });
                    });

                    ElMessage.success(`成功添加 ${newWarehouses.length} 个仓库`);
                    warehouseModalVisible.value = false;
                    selectedWarehouses.value = [];
                };

                // 仓库搜索过滤
                const filteredWarehouses = computed(() => {
                    if (!warehouseSearch.value) {
                        return warehouseList.value;
                    }
                    const search = warehouseSearch.value.toLowerCase();
                    return warehouseList.value.filter(wh =>
                        wh.warehouseName.toLowerCase().includes(search) ||
                        wh.warehouseCode.toLowerCase().includes(search)
                    );
                });

                const searchWarehouses = () => {
                    // 搜索逻辑已在 computed 中实现
                };

                // ---------- 批量设置逻辑 ----------
                const openBatchModal = (type) => {
                    batchType.value = type;
                    batchValue.value = 0;
                    batchModalVisible.value = true;
                };

                const confirmBatchSet = () => {
                    if (batchValue.value === null || batchValue.value === '') {
                        ElMessage.warning('请输入有效的数值');
                        return;
                    }

                    const field = batchType.value === 'upper' ? 'stockUpperLimit' : 'stockLowerLimit';

                    const rowsToUpdate = selectedInventoryRows.value.length > 0
                        ? selectedInventoryRows.value
                        : inventoryData.value;

                    rowsToUpdate.forEach(row => {
                        row[field] = Number(batchValue.value);
                        checkStockLimit(row);
                    });

                    if (selectedInventoryRows.value.length === 0) {
                        if (batchType.value === 'upper') {
                            form.stockMax = Number(batchValue.value);
                        } else {
                            form.stockMin = Number(batchValue.value);
                        }
                    }

                    ElMessage.success('批量设置成功');
                    batchModalVisible.value = false;
                };
                //--------------批次管理-----------------

                // 批次管理相关数据
                const batchManagementVisible = ref(false);
                const batchList = ref([]);
                const currentInventoryRow = ref(null); // 存储当前操作的库存行

                // 点击"批次"输入区域时触发
                const openBatchManagement = (row) => {
                  currentInventoryRow.value = row;
                  // 日期格式化工具函数：确保格式为 yyyy/MM/dd
                  const formatDate = (date) => {
                    if (!date) {
                      const today = new Date();
                      return `${today.getFullYear()}/${String(today.getMonth() + 1).padStart(2, '0')}/${String(today.getDate()).padStart(2, '0')}`;
                    }
                    if (typeof date === 'string') {
                      return date.replace(/-/g, '/');
                    }
                    return `${date.getFullYear()}/${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`;
                  };
                  // 初始化批次列表（回显已有数据或默认生成一条带当前日期的记录）
                  if (row.initialStockBatches && row.initialStockBatches.length > 0) {
                    batchList.value = row.initialStockBatches.map(item => ({
                      ...item,
                      productionDate: formatDate(item.productionDate)
                    }));
                  } else {
                    const today = formatDate(new Date());
                    batchList.value = [{ quantity: 0, batchNo: '', productionDate: today }];
                  }
                  batchManagementVisible.value = true;
                };

                // 添加批次行
                const addBatch = () => {
                  batchList.value.push({ quantity: 0, batchNo: '', productionDate: '' });
                };

                // 移除批次行
                const removeBatch = (index) => {
                  batchList.value.splice(index, 1);
                };

                // 计算总数量
                const calculateTotalQuantity = computed(() => {
                  return batchList.value.reduce((total, item) => total + (item.quantity || 0), 0);
                });

                // 禁止选择未来日期
                const disabledFutureDate = (time) => {
                  // 返回true表示禁用该日期，false表示可选择
                  return time.getTime() > new Date().getTime();
                };

                // 确认批次管理并赋值给库存行
                const confirmBatchManagement = () => {
                  if (currentInventoryRow.value) {
                    currentInventoryRow.value.initialStock = calculateTotalQuantity.value;
                    currentInventoryRow.value.initialStockBatches = [...batchList.value];
                  }
                  batchManagementVisible.value = false;
                };

                // ---------- 库存信息逻辑 ----------
                const handleInventorySelectionChange = (val) => {
                    selectedInventoryRows.value = val;
                };

                // 库存行时初始化批次字段
                const addWarehouse = () => {
                    const newId = inventoryData.value.length > 0
                    ? Math.max(...inventoryData.value.map(item => item.id)) + 1
                    : 1;

                    inventoryData.value.push({
                    id: newId,
                    warehouseName: '',
                    initialStock: 0,
                    initialStockBatches: [], // 新增批次管理字段
                    initialAmount: 0,
                    stockUpperLimit: form.stockMax,
                    stockLowerLimit: form.stockMin,
                    remark: ''
                    });

                    ElMessage.success(`已添加仓库${newId}`);
                };

                const removeWarehouse = () => {
                    if (selectedInventoryRows.value.length === 0) {
                        ElMessage.warning("请先勾选要移除的仓库");
                        return;
                    }

                    inventoryData.value = inventoryData.value.filter(
                        row => !selectedInventoryRows.value.some(s => s.id === row.id)
                    );

                    ElMessage.success(`已移除 ${selectedInventoryRows.value.length} 个仓库`);
                    selectedInventoryRows.value = [];
                };

                const removeInventoryRow = (row) => {
                    inventoryData.value = inventoryData.value.filter(item => item.id !== row.id);
                    ElMessage.success("已移除当前仓库");
                };

                // ---------- 提交逻辑优化 ----------
                const closeDetail = () => {
                    window.history.back();
                };

                const saveAndAdd = async () => {
                    await submitForm(true);
                };

                // 表单验证函数
                const validateForm = () => {
                    // 基础表单校验
                    if (!form.goodsName) {
                        ElMessage.error("请输入货品名称");
                        return false;
                    }
                    if (!form.goodsTypeId || form.goodsTypeId.length === 0) {
                        ElMessage.error("请选择货品类型");
                        return false;
                    }
                    if (!form.customerId) {
                        ElMessage.error("请选择关联客户");
                        return false;
                    }
                    if (!form.supplierId) {
                        ElMessage.error("请选择关联供应商");
                        return false;
                    }

                    // 保质期管理校验
                    if (isShelfLifeEnabled.value) {
                        if (!form.shelfLife || form.shelfLife <= 0) {
                            ElMessage.error("请输入有效的保质期");
                            return false;
                        }
                        if (!form.warningDays || form.warningDays <= 0) {
                            ElMessage.error("请输入有效的预警天数");
                            return false;
                        }
                    }

                    // 新增：库存存在性验证
                    if (inventoryData.value.length === 0) {
                        ElMessage.error("请至少添加一个仓库的库存信息");
                        return false;
                    }

                    // 新增：期初库存合法性验证（开启初始化库存时）
                    if (isInitialStockEnabled.value) {
                        const invalidStockRows = inventoryData.value.filter(row => {
                            return !row.initialStock || row.initialStock <= 0;
                        });
                        if (invalidStockRows.length > 0) {
                            const warehouseNames = invalidStockRows.map(row => row.warehouseName).join("、");
                            ElMessage.error(`仓库【${warehouseNames}】的期初库存必须大于0，请修正`);
                            return false;
                        }
                    }

                    // 库存上下限验证
                    const invalidRows = inventoryData.value.filter(row => {
                        const upper = Number(row.stockUpperLimit) || 0;
                        const lower = Number(row.stockLowerLimit) || 0;
                        return upper < lower;
                    });

                    if (invalidRows.length > 0) {
                        ElMessage.error(`存在${invalidRows.length}条库存上下限设置不合理的数据，请修正后提交`);
                        return false;
                    }

                    return true;
                };

                // 新增：图片上传接口（关联货品ID）
                const uploadImages = async (goodsId) => {
                    const formData = new FormData();
                    uploadedImages.value.forEach((item, index) => {
                        formData.append(`files[${index}]`, item.file);
                    });

                    formData.append('goodsId', goodsId);
                    formData.append('createBy', form.createBy);
                    formData.append('updateBy', form.updateBy);
                    formData.append('createTime', form.createTime.toISOString());
                    formData.append('updateTime', new Date().toISOString());

                    const response = await axios.post('/SysAttachment/UploadAttachment', formData, {
                        headers: { 'Content-Type': 'multipart/form-data' }
                    });

                    if (!response.data.success) throw new Error(response.data.message || '图片上传失败');
                    return response.data.data;
                };

                // 新增：附件上传接口（关联货品ID）
                const uploadFiles = async (goodsId) => {
                    const formData = new FormData();
                    uploadedFiles.value.forEach((item, index) => {
                        formData.append(`files[${index}]`, item.file);
                    });

                    formData.append('goodsId', goodsId);
                    formData.append('createBy', form.createBy);
                    formData.append('updateBy', form.updateBy);
                    formData.append('createTime', form.createTime.toISOString());
                    formData.append('updateTime', new Date().toISOString());

                    const response = await axios.post('/SysAttachment/UploadAttachment', formData, {
                        headers: { 'Content-Type': 'multipart/form-data' }
                    });

                    if (!response.data.success) throw new Error(response.data.message || '附件上传失败');
                    return response.data.data;
                };

                // 新增：更新货品图片路径
                const updateGoodsImage = async (goodsId, imageUrl) => {
                    await axios.post('/BiProduct/UpdateGoodsImage', {
                        goodsId,
                        goodsImagePath: imageUrl,
                        updateBy: form.updateBy,
                        updateTime: new Date().toISOString()
                    });
                };

                // 新增：更新货品附件ID
                const updateGoodsAttachment = async (goodsId, attachmentId) => {
                    await axios.post('/BiProduct/UpdateGoodsAttachment', {
                        goodsId,
                        attachmentId,
                        updateBy: form.updateBy,
                        updateTime: new Date().toISOString()
                    });
                };

                // 优化提交主函数 - 修改为更新逻辑
                const submitForm = async (isAddNew = false) => {
                    if (!validateForm()) return;

                    try {
                        // 1. 构建货品提交数据（图片/附件字段暂空）
                        const submitData = {
                            product: {
                                ...form,
                                goodsTypeId: form.goodsTypeId[form.goodsTypeId.length - 1],
                                goodsImagePath: '', // 暂空，后续更新
                                attachmentId: 0,    // 暂空，后续更新
                                updateTime: new Date().toISOString()
                            },
                            inventoryList: inventoryData.value.map(item => ({
                                warehouseId: item.warehouseId,
                                initialStock: item.initialStock,
                                initialAmount: item.initialAmount,
                                stockUpperLimit: item.stockUpperLimit,
                                stockLowerLimit: item.stockLowerLimit,
                                remark: item.remark
                            }))
                        };

                        // 2. 先更新货品基础信息
                        const goodsResponse = await axios.post('/BiProduct/Edit', { id: form.goodsId, date: submitData.product }, {
                            headers: { 'Content-Type': 'application/json' }
                        });

                        if (goodsResponse.data.code !== 200) {
                            ElMessage.error('货品更新失败：' + goodsResponse.data.msg);
                            return;
                        }

                        const goodsId = form.goodsId;
                        ElMessage.success(`货品更新成功（ID：${goodsId}）`);

                        // 3. 批量上传图片（如有）
                        if (uploadedImages.value.length > 0) {
                            const imageData = await uploadImages(goodsId);
                            if (imageData.length > 0) {
                                await updateGoodsImage(goodsId, imageData[0].attachmentAddress);
                                ElMessage.success(`上传 ${uploadedImages.value.length} 张图片成功`);
                            }
                        }

                        // 4. 批量上传附件（如有）
                        if (uploadedFiles.value.length > 0) {
                            const fileData = await uploadFiles(goodsId);
                            if (fileData.length > 0) {
                                await updateGoodsAttachment(goodsId, fileData[0].attachmentId);
                                ElMessage.success(`上传 ${uploadedFiles.value.length} 个附件成功`);
                            }
                        }

                        // 5. 后续处理
                        ElMessage.success('全部数据更新完成！');
                        if (isAddNew) resetForm();
                        else window.history.back();

                    } catch (error) {
                        console.error('更新失败：', error);
                        ElMessage.error('更新失败：' + (error.message || '网络异常'));
                    }
                };

                // 负数判断通用方法
                const checkNonNegative = (label, value, type, field, scope = null) => {
                  const numValue = Number(value);
                  // 判断是否为负数（排除空值和0）
                  if (!isNaN(numValue) && numValue < 0) {
                    ElMessage.warning(`${label}不能为负数，请输入有效的非负数值`);
                    // 根据不同类型重置数值
                    if (type === 'form') {
                      form[field] = 0;
                    } else if (type === 'row' && scope) {
                      scope.row[field] = 0;
                    } else if (type === 'batch' && scope) {
                      scope.row[field] = 0;
                    }
                  }
                };

                // 重置表单函数
                const resetForm = () => {
                    Object.keys(form).forEach(key => {
                        if (key === 'status') form[key] = '1';
                        else if (key === 'isDelete') form[key] = '0';
                        else if (key === 'goodsTypeId') form[key] = [];
                        else if (key === 'shelfStatus') form[key] = '1';
                        else if (key === 'shelfLifeType') form[key] = '天';
                        else if (typeof form[key] === 'string') form[key] = '';
                        else if (typeof form[key] === 'number') form[key] = 0;
                        else if (form[key] instanceof Date) form[key] = new Date();
                    });
                    inventoryData.value = [];
                    uploadedImages.value = []; // 清空本地图片暂存
                    uploadedFiles.value = []; // 清空本地附件暂存
                    isShelfLifeEnabled.value = true;
                    isInitialStockEnabled.value = true;

                    ElMessage.success('表单已重置，可以添加新货品');
                };

                return {
                    form,
                    goodsTypeTree,
                    customerOptions,
                    supplierOptions,
                    cascaderProps,
                    handleGoodsTypeChange,
                    inventoryData,
                    selectedInventoryRows,
                    handleInventorySelectionChange,
                    addWarehouse,
                    removeWarehouse,
                    removeInventoryRow,
                    uploadedFiles,
                    removeFile,
                    closeDetail,
                    saveAndAdd,
                    submitForm,
                    dictDateOptions,
                    isShelfLifeEnabled,
                    warehouseModalVisible,
                    warehouseList,
                    selectedWarehouses,
                    warehouseSearch,
                    batchModalVisible,
                    batchType,
                    batchValue,
                    batchModalTitle,
                    filteredWarehouses,
                    openWarehouseModal,
                    handleWarehouseSelectionChange,
                    confirmWarehouseSelection,
                    searchWarehouses,
                    openBatchModal,
                    confirmBatchSet,
                    isInitialStockEnabled,
                    checkStockLimit,
                    imageInput,
                    uploadedImages,
                    imagePreviewVisible,
                    previewImageUrl,
                    triggerImageInput,
                    handleImageUpload,
                    previewImage,
                    removeImage,
                    fileInput,
                    triggerFileInput,
                    handleFileUpload,
                    openBatchManagement,
                    confirmBatchManagement,
                    calculateTotalQuantity,
                    removeBatch,
                    addBatch,
                    batchList,
                    batchManagementVisible,
                    disabledFutureDate,
                    checkNonNegative,
                    loading
                };
            }
        });

        app.use(ElementPlus);
        app.mount('#app');
    </script>
</body>
</html>